<template>
  <div class="expense-detail-page">
    <!-- 页面头部 -->
    <van-nav-bar
      title="报销详情"
      left-arrow
      @click-left="onBackClick"
    />
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <van-loading type="spinner" color="#1989fa" />
      <span class="loading-text">加载中...</span>
    </div>
    
    <template v-else>
      <!-- 状态卡片 -->
      <div class="status-card">
        <div class="status-icon" :class="statusClass">
          <van-icon :name="statusIcon" />
        </div>
        <div class="status-info">
          <div class="status-title">{{ statusTitle }}</div>
          <div class="status-desc">{{ statusDesc }}</div>
        </div>
        <div class="status-time">提交时间：{{ expense.submitTime }}</div>
      </div>
      
      <!-- 基本信息卡片 -->
      <div class="info-card">
        <div class="card-title">基本信息</div>
        <div class="info-content">
          <div class="info-item">
            <div class="info-label">报销单号</div>
            <div class="info-value">{{ expense.code }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">报销标题</div>
            <div class="info-value">{{ expense.title }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">所属部门</div>
            <div class="info-value">{{ expense.department }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">报销类型</div>
            <div class="info-value">{{ expense.type }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">报销总额</div>
            <div class="info-value amount">¥{{ expense.totalAmount.toFixed(2) }}</div>
          </div>
          <div class="info-item">
            <div class="info-label">付款方式</div>
            <div class="info-value">{{ expense.paymentMethod }}</div>
          </div>
          <div v-if="expense.paymentMethod === '银行转账'" class="info-item">
            <div class="info-label">银行账号</div>
            <div class="info-value">{{ expense.bankAccount }}</div>
          </div>
          <div v-if="expense.paymentMethod === '银行转账'" class="info-item">
            <div class="info-label">开户银行</div>
            <div class="info-value">{{ expense.bankName }}</div>
          </div>
          <div class="info-item" v-if="expense.notes">
            <div class="info-label">备注说明</div>
            <div class="info-value notes">{{ expense.notes }}</div>
          </div>
        </div>
      </div>
      
      <!-- 报销明细卡片 -->
      <div class="expense-items-card">
        <div class="card-title">报销明细</div>
        <div class="expense-items">
          <div 
            v-for="(item, index) in expense.expenseItems" 
            :key="index"
            class="expense-item"
          >
            <div class="expense-item-header">
              <div class="expense-item-title">{{ item.name }}</div>
              <div class="expense-item-amount">¥{{ item.amount.toFixed(2) }}</div>
            </div>
            
            <div class="expense-item-content">
              <div class="expense-item-detail">
                <span class="detail-label">日期:</span>
                <span class="detail-value">{{ item.date }}</span>
              </div>
              <div class="expense-item-detail" v-if="item.description">
                <span class="detail-label">说明:</span>
                <span class="detail-value desc-value">{{ item.description }}</span>
              </div>
            </div>
            
            <div class="expense-item-images" v-if="item.images && item.images.length > 0">
              <div class="images-title">凭证</div>
              <van-uploader
                :value="item.images"
                :max-count="5"
                :disabled="true"
                :deletable="false"
                multiple
                accept="image/*"
                @click-preview="previewImage(item.images, $event)"
              />
            </div>
          </div>
        </div>
      </div>
      
      <!-- 审批流程卡片 -->
      <div class="approval-card">
        <div class="card-title">审批流程</div>
        <van-steps direction="vertical" :active="activeStep">
          <van-step
            v-for="(step, index) in expense.approvalSteps"
            :key="index"
          >
            <div class="step-content">
              <div class="step-title">{{ step.title }}</div>
              <div class="step-person">{{ step.person }}</div>
              <div class="step-time">{{ step.time || '等待审批' }}</div>
              <div v-if="step.comment" class="step-comment">{{ step.comment }}</div>
            </div>
          </van-step>
        </van-steps>
      </div>
    </template>
    
    <!-- 底部操作栏 -->
    <div class="bottom-action-bar" v-if="!loading">
      <div class="action-buttons">
        <template v-if="expense.status === 'drafting'">
          <van-button type="primary" block @click="handleEdit">继续编辑</van-button>
          <van-button type="danger" plain block @click="handleDelete">删除草稿</van-button>
        </template>
        
        <template v-if="expense.status === 'submitted' || expense.status === 'approving'">
          <van-button type="info" block @click="handleWithdraw">撤回申请</van-button>
        </template>
        
        <template v-if="expense.status === 'rejected'">
          <van-button type="primary" block @click="handleResubmit">重新提交</van-button>
          <van-button type="danger" plain block @click="handleGiveup">放弃申请</van-button>
        </template>
        
        <template v-if="expense.status === 'approved'">
          <van-button type="primary" icon="description" block @click="handleExport">导出报销单</van-button>
        </template>
        
        <template v-if="isApprover && expense.status === 'approving'">
          <van-button type="danger" block @click="handleReject">驳回</van-button>
          <van-button type="primary" block @click="handleApprove">通过</van-button>
        </template>
      </div>
    </div>
    
    <!-- 审批意见弹窗 -->
    <CustomPopup
      v-model:show="showCommentDialog"
      title="审批意见"
      @close="handleDialogCancel"
    >
      <div class="comment-dialog-content">
        <van-field
          v-model="approvalComment"
          type="textarea"
          placeholder="请输入审批意见(选填)"
          rows="4"
          autosize
        />
      </div>
      
      <template #footer>
        <div class="popup-footer-buttons">
          <van-button plain type="default" @click="handleDialogCancel">取消</van-button>
          <van-button type="primary" @click="handleDialogConfirm">确认</van-button>
        </div>
      </template>
    </CustomPopup>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Toast, Dialog, ImagePreview } from 'vant'
import CustomPopup from '@/components/CustomPopup.vue'

export default {
  name: 'ExpenseDetail',
  components: {
    CustomPopup
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const expenseId = route.query.id || route.params.id
    
    // 数据状态
    const loading = ref(true)
    const expense = ref({})
    const isApprover = ref(false)
    const approvalComment = ref('')
    const showCommentDialog = ref(false)
    const currentAction = ref('')
    
    // 状态相关的计算属性
    const statusClass = computed(() => {
      const classMap = {
        'drafting': 'status-drafting',
        'submitted': 'status-submitted',
        'approving': 'status-approving',
        'approved': 'status-approved',
        'rejected': 'status-rejected',
        'cancelled': 'status-cancelled',
        'paid': 'status-paid'
      }
      return classMap[expense.value.status] || 'status-drafting'
    })
    
    const statusIcon = computed(() => {
      const iconMap = {
        'drafting': 'edit',
        'submitted': 'tosend',
        'approving': 'clock-o',
        'approved': 'passed',
        'rejected': 'close',
        'cancelled': 'cross',
        'paid': 'cash-back-record'
      }
      return iconMap[expense.value.status] || 'edit'
    })
    
    const statusTitle = computed(() => {
      const titleMap = {
        'drafting': '草稿',
        'submitted': '已提交',
        'approving': '审批中',
        'approved': '已通过',
        'rejected': '已驳回',
        'cancelled': '已撤销',
        'paid': '已付款'
      }
      return titleMap[expense.value.status] || '草稿'
    })
    
    const statusDesc = computed(() => {
      const descMap = {
        'drafting': '报销单尚未提交，可继续编辑',
        'submitted': '报销单已提交，等待审批',
        'approving': '报销单正在审批流程中',
        'approved': '报销单已通过审批，等待付款',
        'rejected': '报销单被驳回，请查看驳回原因',
        'cancelled': '报销单已撤销',
        'paid': '报销款项已支付'
      }
      return descMap[expense.value.status] || '报销单尚未提交，可继续编辑'
    })
    
    // 当前激活的审批步骤
    const activeStep = computed(() => {
      if (!expense.value.approvalSteps) return 0
      
      const index = expense.value.approvalSteps.findIndex(step => !step.time)
      return index === -1 ? expense.value.approvalSteps.length : index
    })
    
    // 获取报销详情
    const fetchExpenseDetail = () => {
      loading.value = true
      
      // 模拟API请求
      setTimeout(() => {
        expense.value = {
          id: expenseId,
          code: 'BX20230001',
          title: '华南区域客户拜访差旅费',
          type: '差旅费',
          status: 'approving',
          department: '销售部',
          totalAmount: 4235.5,
          paymentMethod: '银行转账',
          bankAccount: '6228 **** **** 1234',
          bankName: '中国建设银行',
          notes: '7月上旬华南区域客户拜访产生的差旅费用，包含机票、酒店及餐饮等',
          submitTime: '2023-07-15 10:30:45',
          submitter: '张三',
          expenseItems: [
            {
              name: '往返机票',
              amount: 2800,
              date: '2023-07-05',
              description: '北京-广州往返商务舱',
              images: ['https://img01.yzcdn.cn/vant/cat.jpeg']
            },
            {
              name: '酒店住宿',
              amount: 980,
              date: '2023-07-05',
              description: '广州某酒店2晚',
              images: ['https://img01.yzcdn.cn/vant/cat.jpeg']
            },
            {
              name: '餐饮费',
              amount: 455.5,
              date: '2023-07-06',
              description: '客户招待餐费',
              images: ['https://img01.yzcdn.cn/vant/cat.jpeg', 'https://img01.yzcdn.cn/vant/cat.jpeg']
            }
          ],
          approvalSteps: [
            {
              title: '提交申请',
              person: '张三',
              time: '2023-07-15 10:30:45'
            },
            {
              title: '部门经理审批',
              person: '李四',
              time: '2023-07-15 14:25:33',
              comment: '费用合理，同意报销'
            },
            {
              title: '财务审批',
              person: '王五',
              time: ''
            },
            {
              title: '出纳支付',
              person: '赵六',
              time: ''
            }
          ]
        }
        
        // 模拟当前用户是否为审批人
        isApprover.value = true
        
        loading.value = false
      }, 1000)
    }
    
    // 预览图片
    const previewImage = (images, index) => {
      ImagePreview({
        images,
        startPosition: index,
        closeable: true
      })
    }
    
    // 返回上一页
    const onBackClick = () => {
      router.back()
    }
    
    // 编辑草稿
    const handleEdit = () => {
      router.push({
        path: '/new/finance/reimbursement/form',
        query: { id: expense.value.id }
      })
    }
    
    // 删除草稿
    const handleDelete = () => {
      Dialog.confirm({
        title: '确认删除',
        message: '确定要删除该报销草稿吗？',
      }).then(() => {
        Toast.loading({
          message: '删除中...',
          forbidClick: true,
          duration: 0
        })
        
        // 模拟删除
        setTimeout(() => {
          Toast.clear()
          Toast.success('删除成功')
          router.replace('/new/finance/reimbursement/list')
        }, 1000)
      })
    }
    
    // 撤回申请
    const handleWithdraw = () => {
      Dialog.confirm({
        title: '确认撤回',
        message: '确定要撤回该报销申请吗？',
      }).then(() => {
        Toast.loading({
          message: '处理中...',
          forbidClick: true,
          duration: 0
        })
        
        // 模拟撤回
        setTimeout(() => {
          Toast.clear()
          Toast.success('撤回成功')
          expense.value.status = 'cancelled'
        }, 1000)
      })
    }
    
    // 重新提交
    const handleResubmit = () => {
      router.push({
        path: '/new/finance/reimbursement/form',
        query: { id: expense.value.id, resubmit: true }
      })
    }
    
    // 放弃申请
    const handleGiveup = () => {
      Dialog.confirm({
        title: '确认放弃',
        message: '确定要放弃该报销申请吗？',
      }).then(() => {
        Toast.loading({
          message: '处理中...',
          forbidClick: true,
          duration: 0
        })
        
        // 模拟放弃
        setTimeout(() => {
          Toast.clear()
          Toast.success('操作成功')
          expense.value.status = 'cancelled'
        }, 1000)
      })
    }
    
    // 导出报销单
    const handleExport = () => {
      Toast('导出功能开发中...')
    }
    
    // 审批通过
    const handleApprove = () => {
      currentAction.value = 'approve'
      showCommentDialog.value = true
    }
    
    // 审批驳回
    const handleReject = () => {
      currentAction.value = 'reject'
      showCommentDialog.value = true
    }
    
    // 处理取消按钮点击
    const handleDialogCancel = () => {
      approvalComment.value = '';
      currentAction.value = '';
      showCommentDialog.value = false;
    };
    
    // 处理确认按钮点击
    const handleDialogConfirm = () => {
      const isApprove = currentAction.value === 'approve';
      
      Toast.loading({
        message: isApprove ? '审批通过中...' : '驳回中...',
        forbidClick: true,
        duration: 0
      });
      
      // 模拟审批操作
      setTimeout(() => {
        Toast.clear();
        
        if (isApprove) {
          Toast.success('审批通过');
          expense.value.status = 'approved';
        } else {
          Toast.success('已驳回');
          expense.value.status = 'rejected';
        }
        
        // 更新审批步骤
        if (expense.value.approvalSteps && activeStep.value < expense.value.approvalSteps.length) {
          const step = expense.value.approvalSteps[activeStep.value];
          step.time = new Date().toLocaleString('zh-CN');
          step.comment = approvalComment.value || (isApprove ? '同意' : '不同意');
        }
        
        // 重置
        approvalComment.value = '';
        currentAction.value = '';
        showCommentDialog.value = false;
      }, 1500);
    };
    
    onMounted(() => {
      fetchExpenseDetail()
    })
    
    return {
      loading,
      expense,
      isApprover,
      statusClass,
      statusIcon,
      statusTitle,
      statusDesc,
      activeStep,
      approvalComment,
      showCommentDialog,
      currentAction,
      previewImage,
      onBackClick,
      handleEdit,
      handleDelete,
      handleWithdraw,
      handleResubmit,
      handleGiveup,
      handleExport,
      handleApprove,
      handleReject,
      handleDialogCancel,
      handleDialogConfirm
    }
  }
}
</script>

<style lang="scss" scoped>
.expense-detail-page {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 80px;
  
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 300px;
    
    .loading-text {
      margin-top: 12px;
      color: #969799;
    }
  }
  
  .status-card {
    margin: 12px;
    background-color: #fff;
    border-radius: 8px;
    padding: 20px 16px;
    display: flex;
    align-items: center;
    position: relative;
    box-shadow: 0 2px 12px rgba(100, 101, 102, 0.08);
    
    .status-icon {
      width: 48px;
      height: 48px;
      border-radius: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      
      &.status-drafting {
        background-color: #969799;
      }
      
      &.status-submitted, &.status-approving {
        background-color: #1989fa;
      }
      
      &.status-approved, &.status-paid {
        background-color: #07c160;
      }
      
      &.status-rejected, &.status-cancelled {
        background-color: #ee0a24;
      }
      
      .van-icon {
        font-size: 24px;
        color: #fff;
      }
    }
    
    .status-info {
      flex: 1;
      
      .status-title {
        font-size: 18px;
        font-weight: 500;
        margin-bottom: 4px;
      }
      
      .status-desc {
        font-size: 13px;
        color: #969799;
      }
    }
    
    .status-time {
      position: absolute;
      right: 16px;
      bottom: 12px;
      font-size: 12px;
      color: #969799;
    }
  }
  
  .info-card, .expense-items-card, .approval-card {
    margin: 12px;
    background-color: #fff;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 12px rgba(100, 101, 102, 0.08);
    
    .card-title {
      font-size: 16px;
      font-weight: 500;
      position: relative;
      padding-left: 12px;
      margin-bottom: 16px;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 4px;
        height: 16px;
        background-color: #1989fa;
        border-radius: 2px;
      }
    }
  }
  
  .info-content {
    .info-item {
      margin-bottom: 12px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .info-label {
        font-size: 13px;
        color: #969799;
        margin-bottom: 4px;
      }
      
      .info-value {
        font-size: 14px;
        color: #323233;
        
        &.amount {
          font-size: 16px;
          font-weight: 500;
          color: #ee0a24;
        }
        
        &.notes {
          white-space: pre-wrap;
          line-height: 1.5;
        }
      }
    }
  }
  
  .expense-items {
    .expense-item {
      margin-bottom: 16px;
      padding: 12px;
      background-color: #f8f8f8;
      border-radius: 8px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .expense-item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        
        .expense-item-title {
          font-weight: 500;
          font-size: 15px;
        }
        
        .expense-item-amount {
          font-weight: 500;
          color: #ee0a24;
        }
      }
      
      .expense-item-content {
        margin-bottom: 10px;
        
        .expense-item-detail {
          margin-bottom: 4px;
          display: flex;
          
          .detail-label {
            min-width: 40px;
            color: #969799;
            font-size: 13px;
          }
          
          .detail-value {
            flex: 1;
            
            &.desc-value {
              white-space: pre-wrap;
            }
          }
        }
      }
      
      .expense-item-images {
        border-top: 1px solid #ebedf0;
        padding-top: 10px;
        
        .images-title {
          font-size: 13px;
          color: #969799;
          margin-bottom: 8px;
        }
      }
    }
  }
  
  .approval-card {
    .step-content {
      padding: 5px 0;
      
      .step-title {
        font-weight: 500;
        font-size: 15px;
        margin-bottom: 4px;
      }
      
      .step-person {
        font-size: 13px;
        margin-bottom: 4px;
      }
      
      .step-time {
        font-size: 12px;
        color: #969799;
        margin-bottom: 4px;
      }
      
      .step-comment {
        background-color: #f7f8fa;
        padding: 8px 12px;
        border-radius: 4px;
        font-size: 13px;
        color: #646566;
        margin-top: 4px;
      }
    }
  }
  
  .bottom-action-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background-color: #fff;
    padding: 12px 16px;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
    z-index: 100;
    
    .action-buttons {
      display: flex;
      gap: 8px;
      
      .van-button {
        flex: 1;
      }
    }
  }
  
  .comment-dialog-content {
    padding: 16px;
  }
}

/* 添加弹窗按钮样式 */
.popup-footer-buttons {
  display: flex;
  gap: 12px;
}

.popup-footer-buttons .van-button {
  flex: 1;
}
</style> 